import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params } from '@angular/router';
import { TimeConfigClass } from '../../common/common-config';
import { StorageService } from "../../common/storage.service";
import { SiteinfoService } from './siteinfo.service';

@Component({
  selector: 'add',
  templateUrl: './siteinfoAdd.component.html',
  // styleUrls: ['./siteinfoList.component.css'],
  providers: [SiteinfoService]
})
export class SiteinfoAddComponent implements OnInit {
  //列表
  timeConfig: any = new TimeConfigClass(); // 时间空间初始化

  constructor(private storage: StorageService, private route: ActivatedRoute, private router: Router, private server: SiteinfoService) {  }

  title: string = '新建';
  objToSubmit: any = {}; // 提交集合
  objToPost: any = {}; 

  templateArr: any = []; // 模板
  tree: any[] = []; //目录
  selectedFiles: any = [];;

  uploadRrl: String = '/file/upload/api'; // 上传图片地址
  imageArr = [];  //标题照片

  ngOnInit() {
    //this.templateArr = [{code:"11111",name:"测试"},{code:"2222",name:"测试22"}]
    this.objToPost = {};
    this.route.params.subscribe((params) => {
      let id = params.id
      if(!id || id<1 ){
        return false;
      }
      this.server.get({id:id}).then(data => {
        if (data.result) {
          this.objToPost = data.data
        } else {
          this.storage.messageService.emit({ severity: 'error', detail:'请求失败!记录不存在或已被删除' })
        }
      });
    });
    this.uploadRrl = this.server.httpService.baseUrl + this.uploadRrl;
//  this.getTemplateArr();
//  this.findTree();
  }
	
	//返回
  returnBtn() {
    this.router.navigate(['../../siteinfo'], { relativeTo: this.route });
  }
    
  /**
   * 保存
   */
  save() {
    let params = this.objToPost;
    //参数验证
    if(!this.checkParams(params)){
      return false;
    }
    console.log(params)
    this.storage.loading();
    this.server.save(params).then(data => {
      this.storage.loadout();
      if (data.result) {
        this.storage.messageService.emit({ severity: 'success', detail: data.msg });
        this.router.navigate(['../../siteinfo'], { relativeTo: this.route });
        console.log('保存成功')
      } else {
        this.storage.messageService.emit({ severity: 'error', detail:'保存失败' })
        console.log('保存失败')
      }
    });
  }

  /**
   * 参数校验
   */
  checkParams(params) {
    let  detail = '';
    if(!params.name){
      detail = '名称';
    }else if(!params.path){
      detail = '文件路径';
    }else if(!params.url){
      detail = '网址';
    }else{
      return true;
    }
    this.storage.messageService.emit({ severity: 'warn', detail: detail+'不能为空！' })
    return false;
  }

  
  /**
  * 上传单张图片验证
  */
  onSelect(event, obj) {
    if (obj.onlyImg == 'true' && event.files.length > 1) {
      this.storage.messageService.emit({ severity: 'error', detail:'只能选择一张图片！' })
      obj.clear();
      return false;
    }
    event.upload();
  }

  /**
  * 图片上传回调函数
  * @param event
  * @param f
  */
  onUpload(event, f) {
    const result = JSON.parse(event.xhr.responseText);
    console.log('上传图片', result);
    if (result && result.result && result.data) {
      this.objToPost[f.cancelLabel] = (this.objToPost[f.cancelLabel] && f.onlyImg != 'true') ? this.objToPost[f.cancelLabel] + ',' + result.data.fileCode : result.data.fileCode;
      this.imgUrlData(result.data.filePath, f.cancelLabel + 'Arr', f.onlyImg);
    };
  }
  
  /**
   * 展示图片数据
   */
  imgUrlData(fileUrl: string, fileArr: any, isClear?: string) {
    if (!fileUrl || !fileArr) {
      return false;
    };
    if (isClear == undefined || isClear == 'true') {
      this[fileArr] = [];
    };
    for (let item of fileUrl.split(',')) {
      this[fileArr] = [...this[fileArr], {
        source: item, thumbnail: item,
        width: '100px', maxWidth: '800px', title: ''
      }];
    };
  }
  /**
  *删除图片并更新对应的图片数据
  * @param event
  * @param f
  */
  removeItem(event, f) {
    //console.log(f);
    let codeArray = this.objToPost[f].split(',');
    codeArray.splice(event.index, 1);
    this.objToPost[f] = codeArray.join(',');
    this[f + 'Arr'] = this[f + 'Arr'].filter((val, index) => index !== event.index);
  }


}
